<template>
  <XenListPage
    title="消息通知"
    :dataList="notificationList"
    :visibleFields="visibleFields"
    :filterFields="filterFields"
    :actions="actions"
    :themeConfig="themeConfig"
    :loading="loading"
    :enableAutoRefresh="false"
    :enableSilentRefresh="true"
    :silentRefreshFn="silentRefreshFn"
    searchPlaceholder="点击筛选通知信息"
    emptyText="暂无通知信息"
    emptyDesc="暂时没有收到任何通知"
    permission-module="sysnotification"
    titleField="Title"
    subtitleField="customSubtitle"
    timeField="SendTime"
    :chatListStyle="true"
    :showEditButton="false"
    :showDeleteButton="false"
    addButtonText="全部已读"
    detailPagePath="/subpkg-sysnotification/details"
    @add="handleMarkAllAsRead"
    @delete="handleDelete"
    @filter="handleFilter"
    @refresh="handleRefresh"
    @silent-refresh="handleSilentRefresh"
  >
    <!-- 自定义插槽图标 -->
    <template #search-icon>
      <uni-icons type="search" size="18" color="#999"></uni-icons>
    </template>
    <template #loading-icon>
      <uni-icons type="spinner-cycle" size="24" color="#666"></uni-icons>
    </template>
    <template #empty-icon>
      <uni-icons type="info" size="48" color="#ccc"></uni-icons>
    </template>
    <template #action-icon-delete>
      <uni-icons type="trash" size="16" color="#FF5252"></uni-icons>
    </template>
    <template #action-icon-edit>
      <uni-icons type="compose" size="16" color="#4CAF50"></uni-icons>
    </template>
    <template #action-icon-view>
      <uni-icons type="eye" size="16" color="#7881de"></uni-icons>
    </template>

    <!-- 消息图标插槽 -->
    <template #avatar-icon="{ item }">
      <view class="message-icon-container">
        <view class="message-icon">
          <!-- 根据消息类型显示不同图标 -->
          <i
            v-if="item.Category?.Icon"
            :class="item.Category.Icon"
            style="font-size: 20px; color: #ffffff"
          ></i>
          <uni-icons
            v-else
            :type="getMessageIcon(item.BusinessType) as any"
            size="20"
            color="#ffffff"
          ></uni-icons>
        </view>
        <!-- 未读标记 -->
        <view v-if="item.Status === '未读'" class="unread-badge"></view>
      </view>
    </template>
  </XenListPage>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { onShow as uniOnShow } from "@dcloudio/uni-app";
import XenListPage from "@/layouts/XenListPage.vue";
import SysNotificationApi from "./api/index";
import type {
  ISysNotificationView,
  ISysNotificationQuery,
} from "./api/interface";

// 创建API实例
const api = SysNotificationApi();

// 根据业务类型获取消息图标
const getMessageIcon = (businessType: string | null): string => {
  if (!businessType) return "chatbubble";

  // 根据业务类型映射图标
  const iconMap: Record<string, string> = {
    系统通知: "gear",
    工作流: "paperplane",
    审批: "checkmarkempty",
    提醒: "alarm",
    公告: "megaphone",
    消息: "chatbubble",
    邮件: "mail",
    任务: "list",
    会议: "calendar",
    文档: "document",
  };

  // 查找匹配的图标
  for (const [key, icon] of Object.entries(iconMap)) {
    if (businessType.includes(key)) {
      return icon;
    }
  }

  return "chatbubble"; // 默认图标
};

// 主题配置
const themeConfig = {
  primaryColor: "#7881de",
  secondaryColor: "#764ba2",
  gradientStart: "#667eea",
  gradientEnd: "#764ba2",
};

// 定义列表显示字段（聊天列表样式不需要显示详细字段）
const visibleFields: any[] = [];

// 定义搜索筛选字段（根据ISysNotificationQuery接口）
const filterFields = [
  {
    key: "Status",
    label: "阅读状态",
    type: "selector",
    placeholder: "请选择阅读状态",
    options: ["未读", "已读"],
  },
  {
    key: "Priority",
    label: "优先级",
    type: "selector",
    placeholder: "请选择优先级",
    options: ["低", "普通", "高", "紧急"],
  },
];

// 定义操作按钮（聊天列表样式主要通过点击列表项进行查看）
const actions = [
  {
    key: "view",
    label: "查看",
    icon: "eye",
    color: "#7881de",
    class: "view-btn",
  },
];

// 通知列表数据
const notificationList = ref<ISysNotificationView[]>([]);

// 处理消息数据，添加自定义副标题
const processNotificationData = (data: ISysNotificationView[]) => {
  return data.map((item) => {
    const senderName = item.SenderName || "系统";
    const content = item.Content || "无内容";

    // 移动端适配：更保守的文本长度控制
    // 发送人名称通常2-4个字符，为内容预留更多空间
    const senderLength = senderName.length + 1; // +1 for ":"
    const maxTotalLength = 20; // 总长度限制为20个字符，适合移动端
    const maxContentLength = Math.max(8, maxTotalLength - senderLength); // 内容最少8个字符

    const truncatedContent =
      content.length > maxContentLength
        ? content.substring(0, maxContentLength) + "..."
        : content;

    return {
      ...item,
      customSubtitle: `${senderName}：${truncatedContent}`,
    };
  });
};

// 处理筛选
const handleFilter = async (filterParams: Record<string, any>) => {
  loading.value = true;
  try {
    // 构建查询参数，映射到API接口需要的字段
    const queryParams: ISysNotificationQuery = {
      Limit: 9999,
      Page: 1,
    };

    // 根据筛选参数构建查询对象
    if (filterParams.Status !== undefined && filterParams.Status !== null) {
      queryParams.Status = filterParams.Status;
    }
    if (filterParams.Priority !== undefined && filterParams.Priority !== null) {
      queryParams.Priority = filterParams.Priority;
    }

    const response = await api.search(queryParams);

    if (response && response.Data) {
      notificationList.value = processNotificationData(response.Data);
    } else {
      notificationList.value = [];
    }
  } catch (error) {
    notificationList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "筛选搜索失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 删除通知
const handleDelete = async (item: ISysNotificationView) => {
  // 调用删除API，传入ID数组
  await api.delete([item.ID!]);

  // 接口调用成功即认为删除成功（无论是否有返回值）
  uni.showToast({ title: "删除成功", icon: "none" });

  // 重新获取数据
  fetchData();
};

// 处理刷新事件
const handleRefresh = () => {
  fetchData();
};

// 处理全部已读
const handleMarkAllAsRead = async () => {
  try {
    loading.value = true;
    await api.MarkAllAsRead();

    // 显示成功提示
    uni.showToast({
      title: "全部已读成功",
      icon: "success",
      duration: 2000,
    });

    // 刷新列表数据
    fetchData();
  } catch (error) {
    // 显示错误提示
    uni.showToast({
      title: "操作失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 加载状态
const loading = ref(false);

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await api.search({
      Limit: 9999,
      Page: 1,
    });

    if (response && response.Data) {
      notificationList.value = processNotificationData(response.Data);
    } else {
      notificationList.value = [];
    }
  } catch (error) {
    notificationList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "获取通知信息失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 静默刷新数据获取函数（供XenListPage组件调用）
const silentRefreshFn = async () => {
  const response = await api.search({
    Limit: 9999,
    Page: 1,
  });
  return response?.Data ? processNotificationData(response.Data) : [];
};

// 处理静默刷新结果
const handleSilentRefresh = (newData: ISysNotificationView[]) => {
  notificationList.value = newData;
};

// 页面加载
onMounted(() => {
  fetchData();
});

// 页面显示处理
uniOnShow(() => {
  // 检查是否是首次加载（列表为空）
  if (notificationList.value.length === 0) {
    fetchData();
  }
});
</script>

<style lang="scss" scoped>
/* 消息图标容器样式 */
.message-icon-container {
  position: relative;
  width: 44px;
  height: 44px;

  .message-icon {
    width: 100%;
    height: 100%;
    border-radius: 22px;
    background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }

  .unread-badge {
    position: absolute;
    top: -2px;
    right: -2px;
    width: 12px;
    height: 12px;
    background: #ff4757;
    border-radius: 50%;
    border: 2px solid #ffffff;
    box-shadow: 0 1px 3px rgba(255, 71, 87, 0.3);
  }
}
</style>
